// pages/teacher/analysis/analysis.js
const app = getApp();

Page({
  data: {
    isLoading: true,
    courseList: [],
    selectedCourseId: null,
    selectedCourseName: '',
    attendanceData: {
      categories: [],
      series: [
        {
          name: '出勤率',
          data: []
        }
      ]
    },
    gradeData: {
      categories: ['不及格', '60-69', '70-79', '80-89', '90-100'],
      series: [
        {
          name: '学生人数',
          data: [0, 0, 0, 0, 0]
        }
      ]
    },
    attendanceOpts: {
      color: ['#1890FF'],
      padding: [15, 15, 0, 15],
      legend: {
        show: true,
        position: 'top',
        fontSize: 12
      },
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        data: [
          {
            min: 0,
            max: 100,
            format: (val) => val + '%'
          }
        ]
      },
      extra: {
        line: {
          type: 'curve',
          width: 3
        }
      }
    },
    gradeOpts: {
      color: ['#6A5ACD'],
      padding: [15, 15, 0, 15],
      legend: {
        show: true,
        position: 'top',
        fontSize: 12
      },
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        data: [
          {
            min: 0
          }
        ]
      },
      extra: {
        column: {
          width: 30
        }
      }
    }
  },

  onLoad: function() {
    this.fetchCourseList();
  },

  onPullDownRefresh: function() {
    this.fetchCourseList();
    wx.stopPullDownRefresh();
  },

  // 获取教师课程列表
  fetchCourseList: function() {
    this.setData({ isLoading: true });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/teacher/courses`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const courses = res.data.data || [];
          this.setData({
            courseList: courses,
            isLoading: false
          });
          
          // 如果有课程，默认选择第一个
          if (courses.length > 0) {
            this.setData({
              selectedCourseId: courses[0].id,
              selectedCourseName: courses[0].name
            });
            this.fetchAnalysisData(courses[0].id);
          }
        } else {
          this.setData({ isLoading: false });
          wx.showToast({
            title: '获取课程列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求课程列表失败:', err);
        this.setData({ isLoading: false });
        
        // 使用模拟数据
        const mockCourses = [
          { id: 1, name: '高等数学', className: '计算机科学1班' },
          { id: 2, name: '线性代数', className: '软件工程2班' },
          { id: 3, name: '数据结构', className: '计算机科学2班' }
        ];
        
        this.setData({
          courseList: mockCourses,
          selectedCourseId: mockCourses[0].id,
          selectedCourseName: mockCourses[0].name
        });
        
        this.fetchAnalysisData(mockCourses[0].id);
      }
    });
  },

  // 获取分析数据
  fetchAnalysisData: function(courseId) {
    this.setData({ isLoading: true });
    
    // 获取考勤数据
    this.fetchAttendanceData(courseId);
    
    // 获取成绩数据
    this.fetchGradeData(courseId);
  },

  // 获取考勤数据
  fetchAttendanceData: function(courseId) {
    wx.request({
      url: `${app.globalData.serverUrl}/api/teacher/analysis/attendance`,
      method: 'GET',
      data: { courseId },
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const data = res.data.data || {};
          this.setData({
            'attendanceData.categories': data.dates || [],
            'attendanceData.series[0].data': data.rates || []
          });
        } else {
          wx.showToast({
            title: '获取考勤数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求考勤数据失败:', err);
        
        // 使用模拟数据
        const mockDates = ['9月1日', '9月8日', '9月15日', '9月22日', '9月29日', '10月6日'];
        const mockRates = [95, 92, 88, 90, 93, 96];
        
        this.setData({
          'attendanceData.categories': mockDates,
          'attendanceData.series[0].data': mockRates
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 获取成绩数据
  fetchGradeData: function(courseId) {
    wx.request({
      url: `${app.globalData.serverUrl}/api/teacher/analysis/grades`,
      method: 'GET',
      data: { courseId },
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const data = res.data.data || {};
          this.setData({
            'gradeData.series[0].data': [
              data.fail || 0,
              data.sixties || 0,
              data.seventies || 0,
              data.eighties || 0,
              data.nineties || 0
            ]
          });
        } else {
          wx.showToast({
            title: '获取成绩数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求成绩数据失败:', err);
        
        // 使用模拟数据
        this.setData({
          'gradeData.series[0].data': [2, 5, 12, 18, 8]
        });
      }
    });
  },

  // 切换课程
  changeCourse: function(e) {
    const courseId = e.detail.value;
    const course = this.data.courseList.find(c => c.id == courseId);
    
    this.setData({
      selectedCourseId: courseId,
      selectedCourseName: course ? course.name : ''
    });
    
    this.fetchAnalysisData(courseId);
  }
});